import gensim
import os

_model=None
_first_build=True
_caches_file='model_caches/common_caches/api_name_word2vec.pt'
_buffer=[]
_threshold=50000


def model(caches_file=None):
    global _model,_first_build,_caches_file
    
    if caches_file is None:
        caches_file=_caches_file
    
    if _model is None:
        if os.path.exists(caches_file):
            _model=gensim.models.Word2Vec.load(caches_file)
            _first_build=False
        else:
            caches_dir=os.path.dirname(caches_file)
            if not os.path.exists(caches_dir):
                os.makedirs(caches_dir)
            _model=gensim.models.Word2Vec(vector_size=256,min_count=2)

    return _model

def train(example_batch):
    global _first_build,_buffer
    
    if example_batch is not None:
        _buffer.extend(example_batch)
    
        if len(_buffer)<_threshold:
            return
    
    if _first_build:
        model().build_vocab(_buffer)
        _first_build=False
    else:
        model().build_vocab(_buffer, update=True)
        
    model().train(_buffer, total_examples=model().corpus_count, epochs=model().epochs)

    del _buffer
    
    _buffer=[]

def save(cache_file=None):
    
    global _buffer,_first_build
    
    if cache_file is None:
        cache_file=_caches_file
        
    if len(_buffer)>0:
        train(None)
        
    model().save(cache_file)

def remove(cache_file=None):
    global _model,_first_build
    if cache_file is None:
        cache_file=_caches_file
        
    if os.path.exists(cache_file):
        os.remove(cache_file)
        
    _model=None
    _first_build=True
    

def eval(word):
    
    if word not in model().wv:
        return None
    
    return model().wv[word]